<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
  <title>Demo</title>
  <style>
  #paper {
    position: relative;
    width: 1200px;
    height: 900px;
  }
  </style>
</head>
<body>
  <div id="paper"></div>
  <script src="/js/d3.js"></script>
  <script src="/js/spritejs.js"></script>
  <script>

const paper = spritejs.Paper2D('#paper').setResolution(800, 600)
const fglayer = paper.layer('fglayer', {handleEvent: true})

const layer = d3.select(fglayer)

const width  = 1330;
const height = 520;

const projection = d3.geoMercator()
  .center([107, 38])
  .scale(width / 2 - 40)
  .translate([width / 4 + 80, height / 2]);

const path = d3.geoPath().projection(projection);

d3.json('/data/mapdata/china.json', (err, data) => {
  if(err) throw new Error(err)

  //console.log(data, path)
  let selectedTarget = null

  layer.selectAll('path')
      .data(data.features)
      .enter()
      .append('path')
      .attr('anchor', 0.5)
      .attr('color', 'black')
      .attr('lineWidth', 1)
      .attr('d', path)
      .attr('renderMode', 'fill')
      .attr('fillColor', '#d1eeee')
      //.attr('bgcolor', 'red')
      .on('click', d => {
        const paths = d3.event.targetPaths

        if(paths.length){
          console.log(d.properties.name)
        }
      })
      .on('mousemove', d => {
        const event = d3.event

        if(event.target !== selectedTarget){
          if(event.targetPaths.length){
            if(selectedTarget){
              selectedTarget.attr('fillColor', '#d1eeee')
            }
            selectedTarget = event.target
            event.target.attr('fillColor', '#c73')
          }
        }
      })
      .select(function() {
        const [x, y] = this.outerSize
        this.attr('translate', [x/2, y/2])
      })
})  

  </script>
</body>
</html>